<template>
  <crud
    entity-name="user"
    :keyword-placeholder="L('UserName')+'/'+L('Name')"
    :delete-confirm="L('DeleteUserConfirm')"
    :dialog-create-title="L('CreateNewUser')"
    :dialog-edit-title="L('EditUser')"
    :request-param="pagerequest"
    :dialog-create-enity-param="{ isActive: true, roleNames: [] }"
    :dialog-enity.sync="editUser"
    @dialogFormClearValidate="handleUserFormClearValidate"
    @dialogFormValidate="handleUserFormValidate"
  >
    <template slot="FilterItems">
      <el-select
        v-model="activeSelected"
        :placeholder="L('Select')"
        clearable
        style="width: 90px"
        class="filter-item"
        @change="handleIsActiveChange"
      >
        <el-option
          :label="L('All')"
          value="All"
        />
        <el-option
          :label="L('Actived')"
          value="Actived"
        />
        <el-option
          :label="L('NoActive')"
          value="NoActive"
        />
      </el-select>
      <el-date-picker
        v-model="creationTime"
        class="filter-item"
        type="daterange"
        align="right"
        unlink-panels
        start-placeholder="创建开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="handleCreationTimeChange"
      />
    </template>

    <template slot="TableColumns">
      <el-table-column
        prop="userName"
        :label="L('UserName')"
        width="180"
      />
      <el-table-column
        prop="emailAddress"
        :label="L('EmailAddress')"
      />
      <el-table-column :label="L('IsActive')">
        <template slot-scope="{row}">
          <el-tag :type="row.isActive | booleanTagFilter">
            {{ row.isActive ? L('Yes') : L('No') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        sortable="custom"
        prop="creationTime"
        :label="L('CreationTime')"
      >
        <template slot-scope="{row}">
          <span>{{ row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </template>

    <template
      slot="CreateOrEditDialog"
      slot-scope="{dialogAction}"
    >
      <el-tabs v-model="activeTag">
        <el-tab-pane
          :label="L('UserDetails')"
          name="first"
        >
          <el-form
            ref="userForm"
            label-width="80px"
            :model="editUser"
            :rules="fromRoles"
          >
            <el-form-item
              :label="L('UserName')"
              prop="userName"
            >
              <el-input
                v-model="editUser.userName"
                :maxlength="32"
                :minlength="2"
              />
            </el-form-item>
            <el-form-item
              :label="L('Name')"
              prop="name"
            >
              <el-input
                v-model="editUser.name"
                :maxlength="32"
              />
            </el-form-item>
            <el-form-item
              :label="L('Surname')"
              prop="surname"
            >
              <el-input
                v-model="editUser.surname"
                :maxlength="1024"
              />
            </el-form-item>
            <el-form-item
              :label="dialogAction"
              prop="emailAddress"
            >
              <el-input
                v-model="editUser.emailAddress"
                :maxlength="32"
              />
            </el-form-item>
            <el-form-item
              v-if="dialogAction == 'create'"
              :label="L('Password')"
              prop="password"
            >
              <el-input
                v-model="editUser.password"
                type="password"
                :maxlength="32"
              />
            </el-form-item>
            <el-form-item
              v-if="dialogAction == 'create'"
              :label="L('ConfirmPassword')"
              prop="confirmPassword"
            >
              <el-input
                v-model="editUser.confirmPassword"
                type="password"
                :maxlength="32"
              />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="editUser.isActive">{{ L('IsActive') }}</el-checkbox>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          :label="L('UserRoles')"
          name="second"
        >
          <el-checkbox-group v-model="editUser.roleNames">
            <el-checkbox
              v-for="role in roles"
              :key="role.id"
              :label="role.normalizedName"
            ><span>{{ role.name }}</span></el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
    </template>
  </crud>
</template>

<script>
import crud from '@/components/CRUD'
import { parseTime } from '@/utils'

export default {
  name: 'Users',
  components: { crud },
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (!value) {
        callback(new Error('Please enter your password again'))
      } else if (value !== this.editUser.password) {
        callback(new Error('The two input passwords do not match!'))
      } else {
        callback()
      }
    }

    return {
      pagerequest: {
        isActive: null,
        from: null,
        to: null
      },
      activeSelected: null,
      creationTime: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      activeTag: 'first',
      editUser: {},
      userRule: {
        userName: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('UserName')), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Name')), trigger: 'blur' }
        ],
        surname: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Surname')), trigger: 'blur' }
        ],
        emailAddress: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Email')), trigger: 'blur' },
          { type: 'email' }
        ]
      },
      newUserRule: {
        userName: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('UserName')), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Name')), trigger: 'blur' }
        ],
        surname: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Surname')), trigger: 'blur' }
        ],
        emailAddress: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Email')), trigger: 'blur' },
          { type: 'email' }
        ],
        password: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Password')), trigger: 'blur' }
        ],
        confirmPassword: { validator: validatePassCheck, trigger: 'blur' }
      }
    }
  },
  computed: {
    fromRoles() {
      return this.action === 'edit' ? this.userRule : this.newUserRule
    },
    roles() {
      // 打开user界面已经初始化过了
      return this.$store.state.user.roles
    }
  },
  async created() {
    await this.$store.dispatch({
      type: 'user/getRoles'
    })
  },
  methods: {
    handleIsActiveChange(val) {
      if (val === 'Actived') {
        this.pagerequest.isActive = true
      } else if (val === 'NoActive') {
        this.pagerequest.isActive = false
      } else {
        this.pagerequest.isActive = null
      }
    },
    handleCreationTimeChange(val) {
      if (val.length > 0) {
        this.pagerequest.from = parseTime(val[0], '{y}-{m}-{d}')
      }
      if (val.length > 1) {
        this.pagerequest.to = parseTime(val[1], '{y}-{m}-{d}')
      }
    },

    handleUserFormClearValidate() {
      this.$refs.userForm.clearValidate()
    },
    handleUserFormValidate(cb) {
      this.$refs.userForm.validate(cb)
    }
  }
}
</script>

